<template>
    <div class="sky" ref="sky">
      <div class="bird" id="bird" ref="bird"></div>
        <section class="pipes-wrap" ref="pipes">
            <div
                    class="pipe-item"
                    v-for="(item, index) in pipeArr"
                    :key="item.id"
                    :id="'pipe' + index"
                    :style="'right:' + item.right + 'px;'"
            >
                <div
                        class="pipe pipe-top"
                        :style="'top:-' + item.top + 'px;'"
                ></div>
                <div
                        class="pipe pipe-bottom"
                        :style="'bottom:-' + item.bottom + 'px;'"
                ></div>
            </div>
        </section>
        <div id="end_game" v-if="gameOver"></div>
    <div class="container" v-if="gameOver">
        <div class="dialog">
            <p class="once-again">本轮分数：{{score}}分</p>
            <p class="once-again">真好玩！</p>
            <p class="once-again">再来一次~~</p>
            <el-button class="once-again-btn" @click="init">开始</el-button>
            <el-button type="danger" @click="back_home">退出</el-button>
        </div>
    </div>
 </div>
</template>

<script>
    import Common from '../components/common'
    const axios=require('axios')
    let rafId = null; // requestAnimationFrame的ID
    let startSpeed = 1;
    const SPEED = 0.04; // 加速度
    const UP = 5.0; // 速度累加上限
    const UP_SUM = 30; // 按一次跳跃的高度
    const BIRD_WIDTH = 50; // 小鸟图片宽50px
    const PIPE_DISTANCE = 350; // 管道之间的横向距离
    let id = 0; // 管道唯一id，从0开始计数
    const randomColour=[
        "#d41313",
        "#e3b200",
        "#e35b00",
        "#00d254",
        "#002ed2",
        "#87c2b9",
        "#703caa",
        "#FFDC35",
        "#93FF93",
        "#d0d0d0"
    ];
    export default {
        name: "Fltingbird",
        data(){
            return{
                username:this.$cookies.get("username"),
                start:false,
                clientWidth: 0,
                clientHeight: 0,
                spaceHeight: [240, 200, 160], // 上管道与下管道之间的距离
                pipeArr: [], // 管道数组
                score: 0, // 得分
                jumpSum: 0, // 当前跳跃相对高度
                jumpFlag: false, // true-按下空格键跳跃上升阶段；false-自由落体阶段
                dropBirdImg: require("../assets/birdimg/dropBird.png"),
                flyBirdImg: require("../assets/birdimg/flyBird.png"),
                //dropBirdImg:require("@/assets/birdimg/birds.png"),
                ctx: null,
                crushBalls: [],
                breaks:[],
                gameOver: false, // 游戏失败的flag，用于停止动画帧
            }
        },

        mounted(){
            let _this=this
            _this.username=Common.username;
            let container=document.getElementById("end_game")
            this.ctx=container
            _this.clientHeight=600
            _this.clientWidth=900
            _this.init();
            document.onkeydown = function(e) {
                let key = window.event.keyCode;
                if (key === 32) {
                    _this.jumpFlag=true
                    //console.log(_this.jumpFlag)
                }
            }
            document.onkeyup=function (e) {
                // _this.pannel.dx=0;
            };

            (function animloop() {
                if (!_this.gameOver) {
                    _this.loop()
                }
                else{
                    // _this.drawCrushBreaks();
                }
                window.requestAnimationFrame(animloop);
            })();
        },

        methods:{
            init(){
              id=0
              this.pipeArr=[]
              this.gameOver=false
                this.$refs.bird.style.top="50%"
                this.$refs.bird.style.left="10%"
                startSpeed=1
                this.addPipe()
            },
            back_home(){
                this.$router.push("/home");
            },
            loop(){
                let _this=this;
                if(_this.jumpFlag){
                    _this.jump();
                }
                let top=_this.$refs.bird.offsetTop;
                //console.log(top)
                if(top>_this.clientHeight-BIRD_WIDTH || top<0){
                    let data=new URLSearchParams()
                    data.append('username',this.username)
                    data.append('flybird',this.score)
                    console.log(this.score)
                    axios.post('/user/updateflybird',data).then(res =>{
                        console.log(res)
                    })
                    _this.gameOver=true
                    this.getCurshBreaks()
                }
                else if(!_this.jumpFlag){
                    _this.$refs.bird.style.background=`url('${_this.dropBirdImg}') no-repeat center/contain`;
                    _this.$refs.bird.style.top = top + startSpeed * startSpeed + "px";
                    if(startSpeed<UP){
                        startSpeed+=SPEED;
                    }
                }
                _this.pipesMove();
            },
            jump() {
                let _this = this;
                _this.$refs.bird.style.background = `url('${_this.flyBirdImg}') no-repeat center/contain`;
                if (_this.jumpSum > UP_SUM) {
                    // 到顶部就落下
                    _this.jumpFlag = false;
                    _this.jumpSum = 0;
                    startSpeed = 1;
                } else {
                    _this.$refs.bird.style.top = _this.$refs.bird.offsetTop - 8 + "px";
                    _this.jumpSum += 8;
                }
            },



            getRandomArbitrary(min, max) {
                return Math.random()*(max-min)+min;
            },

            addPipe(id) {
                let obj = {};
                let top_num = this.getRandomArbitrary(100, 170);
                let height = this.spaceHeight[
                    Math.floor(Math.random() * this.spaceHeight.length)
                    ]; // 随机选取间隙值
                let bottom_num = height - top_num;
                obj.top = top_num;
                obj.id = id;
                obj.right = -(PIPE_DISTANCE / 2);
                obj.bottom = bottom_num;
                this.pipeArr.push(obj);
            },

            pipesMove() {
                let _this = this;
                if (_this.pipeArr.length === 0) {
                    return;
                }
                let right0 = _this.pipeArr[0].right;
                if (right0 > this.clientWidth + 300) {
                    this.pipeArr.shift();
                }
                let right_last = _this.pipeArr[_this.pipeArr.length - 1].right;
                if (right_last >= PIPE_DISTANCE / 2) {
                    id++;
                    this.addPipe(id);
                }
                for (let i = 0; i < _this.pipeArr.length; i++) {
                    //console.log(_this.pipeArr[i].right)
                    // 判断一下小鸟是否接触到了管道，小鸟50*50，left：300px；管道宽100px；管道进入范围right是width-450到width-300
                    if (
                        _this.pipeArr[i].right >= _this.clientWidth - 450 &&
                        _this.pipeArr[i].right <= _this.clientWidth - 300
                    ) {
                        // 该管道进入了小鸟触碰范围
                        let bird_top = _this.$refs.bird.offsetTop;
                        // 12是小鸟图片素材上下有空白间隙
                        if (
                            bird_top <= _this.clientHeight / 2 - _this.pipeArr[i].top ||
                            bird_top >=
                            _this.clientHeight / 2 + _this.pipeArr[i].bottom - BIRD_WIDTH
                        ) {
                            // 碰到了管道
                            this.getCurshBreaks()
                            this.score=0
                            let data=new URLSearchParams()
                            data.append('username',this.username)
                            data.append('flybird',this.score)
                            console.log(this.score)
                            axios.post('/user/updateflybird',data).then(res =>{
                                console.log(res)
                            })
                            _this.gameOver=true
                        }
                    }
                    if (_this.pipeArr[i].right === _this.clientWidth - 300 && _this.pipeArr[i].right === _this.clientWidth - 301) { // 当某个管道刚好在小鸟左边，证明小鸟通过该管道，根据管道id算出小鸟得分
                    }
                    _this.score = _this.pipeArr[i].id ;
                    _this.pipeArr[i].right = _this.pipeArr[i].right + 2; // 管道每帧移动2px
                }
            },

            drawScore(){
                this.ctx.beginPath();
                this.ctx.font="14px Arial";
                this.ctx.fillStyle = "#FFF";
                this.ctx.fillText("分数："+this.score,10,this.clientHeight-14);
                this.ctx.closePath();
            },

            getRandomColor(){
                return randomColour[Math.floor(Math.random() * randomColour.length)];
            },

            getCurshBreaks() {
                let _this = this;
                for (let i = 0; i < 10+_this.score*5; i++) {
                    this.crushBalls.push({
                        x: 5,
                        y: 5,
                        dx: _this.getRandomArbitrary(-6, 6),
                        dy: _this.getRandomArbitrary(-6, 6),
                        r: _this.getRandomArbitrary(1, 4),
                        color: _this.getRandomColor()
                    });
                }
            },

            drawCrushBreaks() {
                this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
                this.crushBalls.forEach(item => {
                    this.ctx.beginPath();
                    this.ctx.arc(item.x, item.y, item.r, 0, 2 * Math.PI);
                    this.ctx.fillStyle = item.color;
                    this.ctx.fill();
                    this.ctx.closePath();
                    item.x += item.dx;
                    item.y += item.dy;
                    if (
                        // 碰到左右墙壁
                        item.x - item.r < 0 ||
                        item.x + item.r > this.clientWidth
                    ) {
                        item.dx = -item.dx;
                    }
                    if (
                        // 碰到上下墙壁
                        item.y - item.r < 0 ||
                        item.y + item.r > this.clientHeight
                    ) {
                        item.dy = -item.dy;
                    }
                });
            },

        }
    }
</script>

<style lang="scss" scoped>
    .sky {
        background-image: url("../assets/birdimg/sky.png");
        width: 900px;
        height: 600px;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
        position: absolute;
        animation: bgMove 8s linear infinite;
        @keyframes bgMove {
            0% {
                background-position: 805px 0;
            }
            100% {
                background-position: 0 0;
            }
        }
        #bird {
            height: 50px;
            width: 50px;
            border-radius: 50%;
            background: url("../assets/bird.png") no-repeat center/contain;
            // 小鸟初始位置
            position: absolute;
        }
        .pipes-wrap {
            position: relative;
            height: 100%;
            overflow: hidden;
            .pipe-item {
                position: absolute;
                height: 100%;
                width: 100px;
                .pipe {
                    width: 100%;
                    height: 50%;
                    position: relative;
                }
                .pipe-top {
                    background-size: 100px;
                    background: url("../assets/birdimg/pipe_b.png") no-repeat top;
                }
                .pipe-bottom {
                    background-size: 100px;
                    background: url("../assets/birdimg/pipe_t.png") no-repeat bottom;
                }
            }
        }
        margin: auto;
        .container {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: rgba(0, 0, 0, 0.3);
            text-align: center;
            font-size: 0;
            white-space: nowrap;
            overflow: auto;
        }
        .container:after {
            content: "";
            display: inline-block;
            height: 100%;
            vertical-align: middle;
        }
        .dialog {
            width: 400px;
            height: 300px;
            background: rgba(255, 255, 255, 0.5);
            box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, 0.3);
            display: inline-block;
            vertical-align: middle;
            text-align: left;
            font-size: 28px;
            color: #fff;
            font-weight: 600;
            border-radius: 10px;
            white-space: normal;
            text-align: center;
            .once-again-btn {
                background: #1f9a9a;
                border: none;
                color: #fff;
            }
        }

    }


</style>